package com.liy.framework.common.token;

import com.liy.framework.common.extvo.LoginInfo;
import com.liy.framework.common.utils.Tools;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64Codec;
import java.util.Date;

public class JwtTokenUtil {

    public static void main(String[] args) throws Exception {
        long s = System.currentTimeMillis();
        LoginInfo loginUser = new LoginInfo();
        loginUser.setId("abc111111111111");
        String token = newToken(loginUser);
        System.out.println("生成时间" + (System.currentTimeMillis() - s));
        System.out.println(token);
        s = System.currentTimeMillis();
        parseToken(token);
        System.out.println("解析时间" + (System.currentTimeMillis() - s));
        s = System.currentTimeMillis();
        System.out.println(Tools.getNewUUID());
        System.out.println("UUID生成时间" + (System.currentTimeMillis() - s));
        System.out.println(parseToken(token));
    }

    public static String newToken(LoginInfo loginUser) {
        Claims claims = null;
        JwtBuilder builder = Jwts.builder().setAudience(loginUser.getId()).setClaims((Claims)claims).setIssuedAt(new Date()).setNotBefore(new Date()).signWith(SignatureAlgorithm.HS256, Base64Codec.BASE64.decode("password"));
        return builder.compact();
    }

    public static Claims parseToken(String jwt) throws Exception {
        Jws<Claims> jws = Jwts.parser().setSigningKey(Base64Codec.BASE64.decode("password")).parseClaimsJws(jwt);
        return (Claims)jws.getBody();
    }
}
